package com.quarkus.resource;

import com.quarkus.entity.User;
import com.quarkus.service.UserService;
import io.quarkus.hibernate.reactive.panache.Panache;
import io.smallrye.mutiny.Uni;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

/**
 * @Author: TongRui乀
 * @Date: 2021/5/22 14:03
 * @description：
 */
@Path("user2")
public class UserResourcePanache {


    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<List<User>> getList(){
        return User.listAll();
    }

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<User> getById(@PathParam("id") Long id){
        return User.findById(id);
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Transactional
    public Uni<Integer> save(User user){
        return user.persist()
                .onItem()
                .transform(Void->1);
//        return Panache.withTransaction(user::persistAndFlush)
//                .replaceWith(1);
    }

    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Transactional
    public Uni<Integer> update(User user){
        return User.update("set name = ?1 where id = ?2", user.getName(), user.getId())
                .onItem()
                .transform(count->{
                    int a = 1/0;
                    return count;
                });
    }

    @PUT
    @Path("update")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<Response> update_(User user) {
        if (user == null || user.getName() == null) {
            throw new WebApplicationException("Fruit name was not set on request.", 422);
        }

        return Panache
                .withTransaction(() -> User.<User> findById(user.getId())
                        .onItem().ifNotNull().invoke(entity -> entity.setName(user.getName()))
                )
                .onItem().ifNotNull().transform(entity -> Response.ok(entity).build())
                .onItem().ifNull().continueWith(Response.ok().status(404)::build);
    }

}
